package com.tian.init;

import com.alibaba.fastjson.JSON;
import com.tian.dto.ChargeStationGunStatusInfo;
import com.tian.entity.ChargeStationGun;
import com.tian.entity.ChargeStationInfo;
import com.tian.enums.ChargerGunStatusEnum;
import com.tian.mapper.ChargeStationGunMapper;
import com.tian.util.StringUtil;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * {@code @description:} 充电桩初始化缓存
 *
 * @author tianwc 公众号：Java后端技术全栈
 * 在线刷题 1200+java面试题和1000+篇技术文章：<a href="https://woaijava.cc/">博客地址</a>
 * {@code @date:} 2024-08-23 10:15
 * {@code @version:} 1.0
 */
@Component
public class StationGunLoadInitCache {
    @Resource
    private ChargeStationGunMapper chargeStationGunMapper;

    @Resource
    private RedissonClient redissonClient;

    public void initDataCache() {
        List<ChargeStationGun> chargeStationGuns = new ArrayList<>();
        for (ChargeStationGun chargeStationGun : chargeStationGuns) {
            // 初始化充电桩枪的状态信息
            RBucket<String> bucket = redissonClient.getBucket("station_gun_" + chargeStationGun.getGunNo());
            ChargeStationGunStatusInfo chargeStationGunStatusInfo = new ChargeStationGunStatusInfo();
            chargeStationGunStatusInfo.setId(chargeStationGun.getId());
            chargeStationGunStatusInfo.setName(chargeStationGun.getGunName());
            chargeStationGunStatusInfo.setGunNo(chargeStationGun.getGunNo());

            RBucket<String> chargeStationInfoCache = redissonClient.getBucket("charge:station:info:" + chargeStationGun.getStationId());
            ChargeStationInfo chargeStationInfo = JSON.parseObject(chargeStationInfoCache.get(), ChargeStationInfo.class);
            chargeStationGunStatusInfo.setStationName(chargeStationInfo.getStationName());
            chargeStationGunStatusInfo.setGunStatus(ChargerGunStatusEnum.OFFLINE.getChargerStatus());
            bucket.set(chargeStationGun.getGunNo());

            RBucket<String> chargerOnlineBucket = redissonClient.getBucket("charger.online_" + chargeStationGun.getGunNo());
            if (StringUtil.isEmpty(chargerOnlineBucket.get())) {
                ChargeStationGunStatusInfo chargerOnline = new ChargeStationGunStatusInfo();
                chargerOnline.setId(chargeStationGun.getId());
                chargerOnline.setName(chargeStationGun.getGunName());
                chargerOnline.setGunNo(chargeStationGun.getGunNo());
                chargerOnline.setStationName(chargeStationInfo.getStationName());
                chargerOnline.setGunStatus(ChargerGunStatusEnum.OFFLINE.getChargerStatus());
                chargerOnlineBucket.set(JSON.toJSONString(chargerOnline));
            }
        }
    }
}
